package com.witmore.skyline.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.witmore.skyline.db.entity.CameraPicDO;
import com.witmore.skyline.db.entity.MessageDO;
import com.witmore.skyline.db.dto.MessageWithPicDTO;
import com.witmore.skyline.db.mapper.MessageMapper;
import com.witmore.skyline.web.config.GlobalAccountSession;
import com.witmore.skyline.web.controller.enums.WitmoreErrorCode;
import com.witmore.skyline.web.controller.vo.param.MessageParam;
import com.witmore.skyline.web.controller.vo.param.MessageParamQuery;
import com.witmore.skyline.web.controller.vo.result.MessageResultVO;
import com.witmore.skyline.web.controller.vo.result.ResponsePageResult;
import com.witmore.skyline.web.controller.vo.result.ResponseResult;
import com.witmore.skyline.web.service.MessageService;
import com.witmore.skyline.web.service.MqttService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Description: MessageServiceImpl
 * Author: 豆子高
 * Date: 2025/5/6 16:39
 */
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private MqttService mqttService;

    @Async("threadPoolExecutor")
    @Override
    public void saveMessage(CameraPicDO cameraPicDO) {
        if (cameraPicDO == null || null == cameraPicDO.getAiLevelType() || cameraPicDO.getAiLevelType() != 2) {
            return;
        }
        // 保存消息
        MessageDO messageDO = new MessageDO();
        messageDO.setOrgId(cameraPicDO.getOrgId());
        messageDO.setMessageType(1);
        messageDO.setMessageTitle("施工安全告警消息");
        messageDO.setMessageContent("指标：" + cameraPicDO.getAiLevel() + "\n分析：" + cameraPicDO.getAiResult());
        messageDO.setMessageStatus(0);
        messageDO.setCreateTime(LocalDateTime.now());
        messageDO.setUpdateTime(LocalDateTime.now());
        messageDO.setBusinessId(cameraPicDO.getId());
        messageMapper.insert(messageDO);
        // 发送MQTT消息-PC实时推送
        String payload = "{\"event\":\"ai_warn_msg\",\"data\":" + JSONObject.toJSONString(messageDO) + "}";
        mqttService.sendMessage(cameraPicDO.getOrgId(), payload);
        // 发送MQTT消息-企微群消息
        Map<String,String> map = new HashMap<>();
        map.put("uuid", UUID.randomUUID().toString());
        map.put("message", messageDO.getMessageContent()
                + "\n消息ID：" + messageDO.getId()
                + "\n图片ID：" + messageDO.getBusinessId());
        map.put("picUrl", cameraPicDO.getPicUrl());
        mqttService.sendWeChatMessage(JSONObject.toJSONString(map));
    }

    @Override
    public ResponsePageResult<MessageResultVO> list(MessageParamQuery paramQuery) {
        // 使用新的查询方法，包含图片地址
        Page<MessageWithPicDTO> messagePage = messageMapper.selectMessagePageWithPicUrl(
            new Page<>(paramQuery.getPage(), paramQuery.getSize()),
            GlobalAccountSession.getUserInfo().getOrgId(),
            paramQuery.getMessageType(),
            paramQuery.getMessageStatus(),
            paramQuery.getDeviceSn(),
            paramQuery.getCameraSn()
        );

        if (messagePage == null) {
            return ResponsePageResult.fail(WitmoreErrorCode.SYSTEM_ERROR);
        }

        // 转换为MessageResultVO
        List<MessageResultVO> resultList = new ArrayList<>();
        for (MessageWithPicDTO messageWithPicDTO : messagePage.getRecords()) {
            MessageResultVO messageResultVO = new MessageResultVO();
            BeanUtils.copyProperties(messageWithPicDTO, messageResultVO);
            resultList.add(messageResultVO);
        }

        // 创建新的分页结果
        Page<MessageResultVO> resultPage = new Page<>(messagePage.getCurrent(), messagePage.getSize(), messagePage.getTotal());
        resultPage.setRecords(resultList);

        return ResponsePageResult.success(resultPage);
    }

    @Override
    public ResponseResult<Void> read(MessageParam messageParam) {
        if (messageParam == null) {
            return ResponseResult.fail(WitmoreErrorCode.PARAM_ERROR);
        }
        // 批量已读和全部已读 至少有一个有值
        if (ObjectUtils.isEmpty(messageParam.getMessageIds()) && messageParam.getReadAll() == null) {
            return ResponseResult.fail(WitmoreErrorCode.PARAM_ERROR);
        }
        MessageDO messageDO = new MessageDO();
        messageDO.setMessageStatus(1);
        messageDO.setUpdateTime(LocalDateTime.now());
        // 批量已读
        if (ObjectUtils.isNotEmpty(messageParam.getMessageIds())) {
            messageMapper.update(messageDO,
                    new LambdaQueryWrapper<MessageDO>()
                            .in(MessageDO::getId, messageParam.getMessageIds())
                            .eq(MessageDO::getOrgId, GlobalAccountSession.getUserInfo().getOrgId())
                            .eq(MessageDO::getMessageStatus, 0)
            );
            return ResponseResult.success();
        }
        // 全部已读
        if (messageParam.getReadAll() != null && messageParam.getReadAll() == 1) {
            messageMapper.update(messageDO,
                    new LambdaQueryWrapper<MessageDO>()
                            .eq(MessageDO::getOrgId, GlobalAccountSession.getUserInfo().getOrgId())
                            .eq(MessageDO::getMessageStatus, 0)
            );
            return ResponseResult.success();
        }

        return ResponseResult.success();
    }
}
